﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace CNative.Logging
{
    /// <summary>
    /// 读取配置文件
    /// </summary>
    public class AppConfigurtaion
    {
        public static IConfiguration Configuration { get; set; }
        static AppConfigurtaion()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载 
            Configuration = new ConfigurationBuilder()
                .SetBasePath(ProcessDirectory)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
        }
        public static string ProcessDirectory
        {
            get
            {
#if NET451
                return AppDomain.CurrentDomain.BaseDirectory;
#else
                return AppContext.BaseDirectory;
#endif
            }
        }

        /// <summary>
        /// GetAppSettings
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultVal"></param>
        /// <returns></returns>
        public static string GetAppSettings(string key, string defaultVal = "")
        {
            try
            {
                var tem = Configuration[key];
                if (string.IsNullOrEmpty(tem))
                    return defaultVal;
                return tem.Trim();
            }
            catch { return defaultVal; }
        }
        /*
         * {
              "Logging": {
                "IncludeScopes": false,
                "LogLevel": {
                  "Default": "Warning"
                }
              },
              "ConnectionStrings": {
                "CxyOrder": "Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;"
              },
              "Appsettings": {
                "SystemName": "PDF .NET CORE",
                "Date": "2017-07-23",
                "Author": "PDF"
              },
              "ServiceUrl": "https://www.baidu.com/getnews"
            }

        AppConfigurtaionServices.Configuration.GetConnectionString("CxyOrder"); 
        //得到 Server=LAPTOP-AQUL6MDE\\MSSQLSERVERS;Database=CxyOrder;User ID=sa;Password=123456;Trusted_Connection=False;
 

        读取一级配置节点配置:
        AppConfigurtaionServices.Configuration["ServiceUrl"];

        读取二级子节点配置
        AppConfigurtaionServices.Configuration["Appsettings:SystemName"];
        AppConfigurtaionServices.Configuration["Appsettings:Author"];
        */
    }
}
